package com.deyuanyun.pic.web.interceptor;

import com.deyuanyun.pic.cache.SessionCacheSupport2;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

public class ParameterFilter extends HttpServletRequestWrapper {

    private Map<String, String[]> params;

    public ParameterFilter(HttpServletRequest request,Map<String, String[]> newParams) {
        super(request);

        this.params = newParams;
        // RequestDispatcher.forward parameter
        renewParameterMap(request);
    }

    @Override
    public String getParameter(String name) {
        String result = "";

        Object v = params.get(name);
        if (v == null) {
            result = null;
        } else if (v instanceof String[]) {
            String[] strArr = (String[]) v;
            if (strArr.length > 0) {
                result =  strArr[0];
            } else {
                result = null;
            }
        } else if (v instanceof String) {
            result = (String) v;
        } else {
            result =  v.toString();
        }

        return result;
    }

    @Override
    public Map getParameterMap() {
        return params;
    }

    @Override
    public Enumeration getParameterNames() {
        return new Vector(params.keySet()).elements();
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] result = null;

        Object v = params.get(name);
        if (v == null) {
            result =  null;
        } else if (v instanceof String[]) {
            result =  (String[]) v;
        } else if (v instanceof String) {
            result =  new String[] { (String) v };
        } else {
            result =  new String[] { v.toString() };
        }

        return result;
    }

    private void renewParameterMap(HttpServletRequest req) {

        String queryString = req.getQueryString();

        if (queryString != null && queryString.trim().length() > 0) {
            String[] params = queryString.split("&");

            for (int i = 0; i < params.length; i++) {
                int splitIndex = params[i].indexOf("=");
                if (splitIndex == -1) {
                    continue;
                }

                String key = params[i].substring(0, splitIndex);

                if (!this.params.containsKey(key)) {
                    if (splitIndex < params[i].length()) {
                        String value = params[i].substring(splitIndex + 1);
                        this.params.put(key, new String[] { value });
                    }
                }
            }
        }

        if(this.params==null || this.params.size()<=0){return;}
        Map<String, String[]> pp=new HashMap<String, String[]>();
        /**遍历参数map，兵替换掉危险字符*/
        for (Map.Entry<String, String[]> entry: this.params.entrySet()) {
            String key = entry.getKey();

            if (safelessKey.contains(key)){
                continue;
            }

            String[] value1 = entry.getValue();

            String[] stringsValue=new String[value1.length];
            if (value1!=null && value1.length>0){
                for (int i=0;i<value1.length;i++){
                    stringsValue[i]=replaceSpecChar(value1[i]);
                }
            }
            pp.put(key,stringsValue);
        }
        this.params=pp;
    }
    private static String replaceSpecChar(String str) {

        if(StringUtils.isNotEmpty(str)) {
            if (str.length()>4000){
                str="";
            }
            for (String s : safeless) {
                str=str.replaceAll("(?i)"+s,"");
            }
        }
        if ("".equalsIgnoreCase(str)){
            str=null;
        }
        return str;
    }

    private static List<String> safelessKey=new ArrayList<>();
    static {
        safelessKey.add(SessionCacheSupport2.USERLOGINID);
    }

    public static String[] safeless = {
            "<script",   //需要拦截的JS字符关键字
            "</script",
            "<iframe",
            "</iframe",
            "<frame",
            "</frame",
            "set-cookie",
            "%3cscript",
            "%3c/script",
            "%3ciframe",
            "%3c/iframe",
            "%3cframe",
            "%3c/frame",
            "src=\"javascript:"
            // "<body",
            // "</body",
            // "%3cbody",
            // "%3c/body",
            //"<",
            //">",
            //"</",
            //"/>",
            //"%3c",
            //"%3e",
            //"%3c/",
            //"/%3e"
    };
}